_package("caf.core");

_import("caf.core.Application");
_import("caf.core.MobileService");
_import("caf.mui.LinkButton");
_import("caf.mui.ListBox");
_import("caf.mui.ScrollView");
_import("caf.mui.Dialog");
_import("caf.ui.Button");
_import("caf.ui.DeckView");
_import("caf.ui.DeckViewList");
_import("caf.ui.MessageBox");
_import("caf.ui.DialogueBox");
_import("caf.ui.DeckPage");
_import("caf.ui.PaneShell");

/**
 * CAF框架应用基类
 */
_class("AppBase", Application, function(){
	this.__conf__({
		"tags": [
			{"tag": "a:listbox"     , "clazz": "ListBox"     },
			{"tag": "a:linkbutton"  , "clazz": "LinkButton"  },
			{"tag": "a:scrollview"  , "clazz": "ScrollView"  },
			{"tag": "a:button"      , "clazz": "Button"      },
			{"tag": "a:deckview"    , "clazz": "DeckView"    },
			{"tag": "a:deckviewlist", "clazz": "DeckViewList"}
		],
		//"page": [],
		"dialog": [
			{"id": "dialog"   , "clazz": "Dialog"     },
			{"id": "msgbox"   , "clazz": "MessageBox" },
			{"id": "confirm"  , "clazz": "DialogueBox"}/*,
			{"id": "dlg_login", "clazz": "DlgLogin"   }*/
		]
	});
	this._init = function(){
		_super._init.call(this);
		this._useProxy = true;  //启用代理跨域

		this._mobile = null;
		this._deckPage = null;  //Page对象管理组件
		this._apiId = 0;        //api编号
		this._apiHash = {};     //api哈希
		this._apiFail = [];     //错误回调cbid
		this._token = "";
		this._noToken = "false";
	};
	this.init = function(){
		_super.init.apply(this, arguments);
		if(runtime.getConfData("use_shell")){
			runtime.getWorkspace().createRootPane(PaneShell);
		}
		this._mobile = new MobileService();
		//初始化contentPane
		this._deckPage = new DeckPage();
		this.setContentPane(this._deckPage);
		/* test
		runtime.log("log");
		runtime.warning("warning");
		//runtime.error("error");
		window.abc = function(base64code){
			runtime.log(base64code.substr(0, 50) + "...");
		};
		this._mobile.request("Multimedia.takePhoto", "abc");
		*/
	};
	this.reset = function(){
		//_super.reset.apply(this, arguments);
		this._deckPage.reset();
	};
	this.dispose = function(){
		for(var k in this._apiHash){
			window[k] = null;
			delete window[k];
			this._apiHash[k] = null;
			delete this._apiHash[k];
		}
		this._deckPage.dispose();
		this._deckPage = null;
		this._mobile.dispose();
		this._mobile = null;
		_super.dispose.apply(this);
	};
	/**
	 * 加载APP配置数据
	 * @param {String} appkey 应用的标志
	 * @param {Object} hash 默认值
	 */
	this.loadConfigData = function(appkey, hash){
		var v = this._storage.getItem(appkey + "_conf");
		var conf = runtime.parseJson(v) || {};
		for(var k in hash){
			if(!(k in conf)){
				conf[k] = hash[k];
			}
		}
		this._model.setConf(conf);
	};
	/**
	 * 保存APP配置数据
	 * @param {String} appkey 应用的标志
	 */
	this.saveConfigData = function(appkey){
		var v = JSON.stringify(this._model.getConf());
		this._storage.setItem(appkey + "_conf", v);
	};
	this.loadCache = function(appkey, hash){
		var v = this._storage.getItem(appkey + "_conf");
		var conf = runtime.parseJson(v) || {};
		for(var k in hash){
			if(!(k in conf)){
				conf[k] = {
					"value" : hash[k],
					"expire": -1       //默认永不过期
				};
			}
		}
		this._model.setConf(conf);
	};
	this.saveCache = function(appkey){
		this.saveConfigData(appkey);
	};
	/*
	this.getToken = function(){
		if(CloudAPI){
			return CloudAPI.PIM.getTYToken("false");
		}else{
			return "mock";
		}
	};
	*/
	this.getTYToken = function(flag){
		//this._model.getConfData("taoyunid")
		//this._model.setConfData("taoyunid", "0");  //已经绑定淘云帐号
		//this._model.setConfData("taoyunid", CloudAPI.PIM.peekTYToken());
		var token = CloudAPI.PIM.getTYToken("" + flag);
		return token === "false" ? "0" : token;
	};
	this.peekTYToken = function(){
		var token = CloudAPI.PIM.peekTYToken();
		return token === "false" ? "0" : token;
	};
	this.createApi = function(name, func){
		var id = this._apiId++;
		var k = "__caf_" + id + "_" + name;
		this._apiHash[id] = func;
		window[k] = func;
		return k;
	};
	/**
	 * @deprecated
	 */
	this.requestTYToken = function(flag, agent, func){
		this.apiInvoke("token", [flag], agent, func);
	};
	this.regApiFailCallback = function(agent, func){
		this._apiFail.push(runtime._task.add(agent, func));
	};
	this.failCallback = function(cmd, msg){
		for(var i = 0, len = this._apiFail.length; i < len; i++){
			runtime._task.send(this._apiFail[i], [cmd, msg], true);
		}
	};
	/**
	 * 通用的本地API调用接口(本地异步服务请求)
	 * @param {String} cmd 请求命令
	 * @param {Array} argv 请求参数
	 * @param {Object} agent 代理对象
	 * @param {Function} func 回调函数
	 */
	this.apiInvoke = function(cmd, argv, agent, func){
		var cbid = runtime._task.add(agent, func);
		var _this = this;
		switch(cmd){
		case "token":  //获取token
			//argv: [flag]
			var flag = argv[0];
			this._token = CloudAPI.PIM.peekTYToken();  //this.peekTYToken()
			if(flag || this._token == this._noToken){
				var fail = arguments[4];  //自定义的错误处理
				if(fail){
					runtime.warning("apiInvoke错误回调已经统一使用app.regApiFailCallback处理，请重构之");
				}
				CloudAPI.PIM.getTYToken(flag ? "true" : "false",
					this.createApi("token_suc", function(token){
						_this._token = token;
						runtime._task.send(cbid, token);
					}),
					this.createApi("token_fail", function(msg){
						if(fail && typeof fail == "function"){
							fail(msg);
						}
						_this.failCallback(cmd, msg);
						runtime._task.cancel(cbid);
						runtime.error(msg);
					})
				);
			}else{
				runtime._task.send(cbid, this._token);
			}
			break;
		case "sign":  //获取sign
			//argv: [flag]
			CloudAPI.PIM.getSign(argv[0] ? "true" : "false",
				this.createApi("sign_suc", function(sign){
					//sign = "hRJ2I5oyGUCkEZTPvMLjrl7H0wfxYAsu";
					runtime._task.send(cbid, sign);
				}),
				this.createApi("sign_fail", function(msg){
					_this.failCallback(cmd, msg);
					runtime._task.cancel(cbid);
					runtime.error("获取sign失败:" + msg);
				})
			);
			break;
		case "position":  //获取当前定位
			//argv: []
			var fail = arguments[4];  //自定义的错误处理
			if(fail){
				runtime.warning("apiInvoke错误回调已经统一使用app.regApiFailCallback处理，请重构之");
			}
			CloudAPI.Device.DeviceStateInfo.getCurrentPosition(
				this.createApi("pos_suc", function(position){
					runtime._task.send(cbid, position);
				}),
				this.createApi("pos_fail", function(msg){
					if(fail && typeof fail == "function"){
						fail(msg);
					}
					_this.failCallback(cmd, msg);
					runtime._task.cancel(cbid);
					runtime.error(msg);
				})
			);
			break;
		case "download":  //下载文件
			//argv: [remoteUrl,fileName]
			var progress = arguments[4];  //进度回调
			CloudAPI.Utility.download(argv[0], argv[1],
				this.createApi("down_suc", function(msg){
					runtime._task.send(cbid, msg);
				}),
				this.createApi("down_fail", function(msg){
					_this.failCallback(cmd, msg);
					runtime._task.cancel(cbid);
					runtime.error(msg);
				}),
				this.createApi("down_progress", function(msg){
					progress.call(agent, parseInt(msg));
				})
			);
			break;
		case "upload":  //上传文件
			//argv: [sourceUrl, remoteUrl, fileKey, [option1key, option1value ... ]]
			var progress = arguments[4];  //进度回调
			CloudAPI.Utility.upload(argv[0], argv[1], argv[2],
				this.createApi("up_suc", function(msg){
					runtime._task.send(cbid, msg);
				}),
				this.createApi("up_fail", function(msg){
					_this.failCallback(cmd, msg);
					runtime._task.cancel(cbid);
					runtime.error(msg);
				}),
				this.createApi("up_progress", function(msg){
					progress.call(agent, parseInt(msg));
				}),
				argv[3]
			);
			break;
		case "scanBarCode":  //扫描barcode
			//argv: [title]
			CloudAPI.Device.scanBarCode(argv[0] || "",
				this.createApi("scan_suc", function(msg){
					runtime._task.send(cbid, msg);
				}),
				this.createApi("scan_fail", function(msg){
					_this.failCallback(cmd, msg);
					runtime._task.cancel(cbid);
					runtime.error(msg);
				})
			);
			break;
		case "bindTaobao":  //绑定淘宝帐号
			//argv: []
			CloudAPI.PIM.bindTaobao(
				this.createApi("bindtb_suc", function(msg){
					runtime._task.send(cbid, msg);
				}),
				this.createApi("bindtb_fail", function(msg){
					_this.failCallback(cmd, msg);
					runtime._task.cancel(cbid);
					runtime.error(msg);
				})
			);
			break;
		case "pay":  //支付宝支付接口
			//argv: []
			CloudAPI.Alipay.pay(argv[0], argv[1], 
				this.createApi("pay_suc", function(msg){
					runtime._task.send(cbid, msg);
				}),
				this.createApi("pay_fail", function(msg){
					_this.failCallback(cmd, msg);
					runtime._task.cancel(cbid);
					runtime.error(msg);
				})
			);
			break;
		case "app_mod":  //CAP拖拽编辑
			//argv: [json]
			CloudAPI.Device.sendCloudAppInfo(JSON.stringify(argv[0]),
				this.createApi("app_mod", function(ret){
					runtime._task.send(cbid, ret);
				})
			);
			break;
		}
		return cbid;
	};
	/**
	 * 网络调用接口
	 * ev的格式：{type:s,params:{method, url, params, type, agent, func}}
	 */
	this.onBeforeNetInvoke = function(ev){
		ev.req.beforeInvoke();
	};
	this.checkJsonData = function(json){
		if(!json){
			runtime.error("[AppBase::checkJsonData]json参数格式错误");
			return false;
		}
		if(json.code >= 0){
			return true;
		}else{
			var str = "[AppBase::checkJsonData]json format error"
				+ "\njson.msg=" + json.msg
				+ "\njson.data=" + json.data;
			runtime.error(str);
			return false;
		}
	};
	/**
	 * Page对象导航(简单模拟页面导航功能)
	 * @param {String} pid Page编号
	 * @param {Object} params 传递给page对象的参数
	 * @param {Number} offset 历史纪录偏移量，默认0
	 */
	this.navPage = function(pid, params, offset){
		this._deckPage.navPage.apply(this._deckPage, arguments);
	};
	this.doAction = function(act, sender){
		var key = "do_" + act;
		if(key in this && typeof this[key] == "function"){
			var ret = this[key](act, sender);
			return typeof ret == "boolean" ? ret : false;
		}else{
			runtime.error("[AppBase::doAction]未定义的act=" + act);
			return false;
		}
	};
	this.showMsgBox = function(title, msg, layout){
		//var dlg = new DialogueBox(title, msg, this, "connectInternet");
		//dlg.create(runtime.getWorkspace());
		//var msgbox = new MessageBox(title, msg, layout);
		//msgbox.create(runtime.getWorkspace());
		var params = {
			"title" : title,
			"msg"   : msg,
			"layout": layout
		};
		this.dlgInvoke("msgbox", this, params, this, function(dlg, act){
		});
	};
});